import { defineStore } from 'pinia';
import { queryGetPoints, queryUserInfo, type LoginRes, type RegisterRes, type UserInfo } from '~/apis/auth';

export const useUserStore = defineStore('userStore', () => {
  const token = ref('');
  const refreshToken = ref('');
  const userInfo = ref<Partial<UserInfo>>({});
  const isLoggedIn = computed(() => !!token.value);

  const onRegister = async (res: RegisterRes) => {
    token.value = res.token;
    refreshToken.value = res.refreshToken;
    userInfo.value = res.userInfo;
    localStorage.setItem('token', res.token);
    localStorage.setItem('refreshToken', res.refreshToken);
    localStorage.setItem('userInfo', JSON.stringify(res.userInfo));
  };

  const onLogin = async (res: LoginRes) => {
    token.value = res.token;
    refreshToken.value = res.refreshToken;
    localStorage.setItem('token', res.token);
    localStorage.setItem('refreshToken', res.refreshToken);
    await onGetUserInfo();
  };

  const onLogout = () => {
    token.value = '';
    refreshToken.value = '';
    userInfo.value = {};
    localStorage.removeItem('token');
    localStorage.removeItem('refreshToken');
    localStorage.removeItem('userInfo');
  };

  const onGetUserInfo = async () => {
    const res = await queryUserInfo();
    userInfo.value = res.data;
    localStorage.setItem('userInfo', JSON.stringify(res.data));
  };

  // 初始化方法 - 从localStorage恢复状态
  const init = async () => {
    if (import.meta.client) {
      const _userInfo = localStorage.getItem('userInfo');
      const _token = localStorage.getItem('token');
      const _refreshToken = localStorage.getItem('refreshToken');
      if (_userInfo) userInfo.value = JSON.parse(_userInfo);
      if (_token) token.value = _token;
      if (_refreshToken) refreshToken.value = _refreshToken;
      if (_token) await onGetUserInfo();
    }
  };

  return {
    token,
    refreshToken,
    isLoggedIn,
    userInfo,
    onRegister,
    onLogin,
    onLogout,
    onGetUserInfo,
    init,
  };
});
